# coding=utf-8
import cv2
import dlib
import numpy as np
import os,glob
from skimage import io



detector =dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('model/shape_predictor_68_face_landmarks.dat')
face_rec = dlib.face_recognition_model_v1("model/dlib_face_recognition_resnet_model_v1.dat")

#1.检测人脸库中人脸  check_face_lib()
from face_lib_featuare_util import load_face_lib


#2.检测要识别的图片中人脸
def get_input_face(img_path):
    print("检测要识别的图片中人脸")
    io.imread(img_path )
    img = io.imread(img_path)
    faces = detector(img, 1)
    for i, face in enumerate(faces):
        shape = predictor(img, face)
    face_descriptor = face_rec.compute_face_descriptor(img,shape)
    return face_descriptor


def cal_distance(faced_descriptors,faced_descriptor):
    dists =[]
    print("计算欧式距离")
    d = np.array(faced_descriptor)
    # 计算欧式距离

    for i in faced_descriptors:

        # linalg=linear(线性)+algebra(代数)，norm则表示范数。默认是二范数(参fanshu.jpg)，默认情况下是求整个矩阵元素平方和再开根号
        # x_norm=np.linalg.norm(x，ord=None，axis=None，keepdims=False)
        f_d =np.array(i)
        dist = np.linalg.norm(f_d - d)

        dists.append(dist)
    return dists


def get_recongnition_result(distance_list,labels):
    print("设置阀值,判定结果")

    exist_face = False
    for distance in distance_list:
        if distance < 0.5:
            exist_face = True

    if exist_face:
        print("该人脸库中存在!")
        index =distance_list.index(min(distance_list))
        print('该人物是:',labels[index])
    else:
        print("该人脸库中不存在!")




def recognition_face(img_path):
    #1.检测人脸库中人脸check_face_lib()
    faced_descriptors, labels =load_face_lib()
    #2.检测要识别的图片中人脸get_input_face(
    faced_descriptor =get_input_face(img_path)
    #3.人脸比对，计算欧式距离
    dists =cal_distance(faced_descriptors,faced_descriptor)
    print(dists)

    #4.设置阀值，判定绍果
    get_recongnition_result(dists,labels)

if __name__=='__main__':
    recognition_face_path = "C:\\Users\\asus\\Pictures\\Camera Roll\\face/"
    img_file_name = input("输入要识别的文件名:")
    recognition_face(recognition_face_path + img_file_name)

